<?php include "classes.inc" ?>
<?php include "constants.inc" ?>
<?php session_start(); ?>
<?php
    $poll_id = $_POST['id'];
    $option_id = $_POST['option'];
    $comment = trim($_POST['comment']);
    
    $ip= $_SERVER['REMOTE_ADDR'];
    
    if ( !empty($poll_id) && !empty($option_id) ) {
        $user = $_SESSION['user'];

        $connect = mysql_connect(DB_SERVER, DB_USER, DB_PWD);
        mysql_select_db(DB_CATALOG);
        $result = mysql_query("SET AUTOCOMMIT=0", $connect);
        $result = mysql_query("BEGIN", $connect);
        
        $query = sprintf("select count(1) as voted from poll_visitors where poll_id = %u and visitor = '%s'", $poll_id, $ip);
        $result = mysql_query($query, $connect);
        $row = mysql_fetch_assoc($result);
        $voted = $row['voted'];
        if ($voted == 0) {
              $query = "UPDATE poll_option SET count = count + 1 WHERE poll_option_id = ".$option_id;
        
            if ($result != mysql_query($query, $connect)) {
                $err = mysql_error();
                mysql_query("ROLLBACK", $connect);
                echo "Keuze kon niet worden opgeslagen: ".$err;
            }
            
            if (!empty($comment)) {
                $encodedComment = mysql_real_escape_string(utf8_decode($comment));
                
                $query = "select color from poll_option where poll_option_id = ".$option_id;
                $result = mysql_query($query, $connect);
                $row = mysql_fetch_assoc($result);
                $choice_color = $row['color'];
                
                $query = sprintf("INSERT INTO poll_comment (poll_id, comment, choice_color) VALUES (%u, '%s', '%s')", $poll_id, $encodedComment, $choice_color);
                if ($result != mysql_query($query, $connect)) {
                    $err = mysql_error();
                    mysql_query("ROLLBACK", $connect);
                    echo "Commentaar kon niet worden opgeslagen: ".$err;
                }
            }
            
            $query = sprintf("insert into poll_visitors (poll_id, visitor) values(%u, '%s')", $poll_id, $ip);
            mysql_query($query, $connect);

            mysql_query("COMMIT", $connect);
        }
        
        
        
    } else {
        echo "Uw keuze is niet herkend [id=".$poll_id.",keuze=".$comment."]";
    }
?>
